package com.yu.xcx.util;

import com.google.gson.Gson;
import com.yu.xcx.entity.SendParam;
import com.yu.xcx.entity.SendReturn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Map;

@Component
public class SendUtils {

    private static RestTemplate restTemplate;

    @Autowired
    ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        SendUtils.restTemplate = applicationContext.getBean(RestTemplate.class);
    }

    private static Gson gson = new Gson();


    /**
     * 发送get请求
     * @param send
     * @return
     */
    public static SendReturn sendGet(SendParam send){
        String url = send.getUrl()+"?";
        if(send.getGetParam()!=null){
            Map<String,String> map = send.getGetParam();
            for(Map.Entry<String,String> entity : map.entrySet()){
                url += entity.getKey()+"="+entity.getValue()+"&";
            }
            url = url.substring(0,url.length()-1);
        }

        SendReturn sendReturn = new SendReturn();
        try{
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            if(send.getClassTr()!=null){
                Object o = gson.fromJson(responseEntity.getBody(),send.getClassTr());
                sendReturn.setObj(o);
            }
            sendReturn.setStatusCode(responseEntity.getStatusCode());
            sendReturn.setStatusCodeValue(responseEntity.getStatusCodeValue());
            sendReturn.setReturnString(responseEntity.getBody());
        }catch (Exception e){
            System.out.println(e);
            sendReturn.setSuccess(false);
        }
        return sendReturn;
    }


    /**
     * 发送post请求
     * @param send
     * @return
     */
    public static SendReturn SendPost(SendParam send){
        SendReturn sendReturn = new SendReturn();
        try{
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(send.getUrl(),send.getPostParam(),String.class);
            if(send.getClassTr()!=null){
                Object o = gson.fromJson(responseEntity.getBody(),send.getClassTr());
                sendReturn.setObj(o);
            }
            sendReturn.setStatusCode(responseEntity.getStatusCode());
            sendReturn.setStatusCodeValue(responseEntity.getStatusCodeValue());
            sendReturn.setReturnString(responseEntity.getBody());
        }catch (Exception e){
            System.out.println(e);
            sendReturn.setSuccess(false);
        }
        return sendReturn;
    }




}